package cn.stronglink.esm27.collection.iot.devices.algorithmservice.request.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.task.AutoPushGasAlgorithmDatasTask;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

/**
 * 关闭气体扩散推送任务
 * @author yuzhantao
 *
 */
public class CloseGasDispersionAlgorithmServiceHandle implements IMessageHandle<MQMessageOfESM27, Object> {
	protected static Logger logger = LogManager.getLogger(CloseGasDispersionAlgorithmServiceHandle.class.getName());
	protected TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected final static String ACTION_CODE="CloseGasDispersionAlgorithmService";
	protected AutoPushGasAlgorithmDatasTask autoPushGasAlgorithmDatasTask = (AutoPushGasAlgorithmDatasTask)ContextUtils.getBean("autoPushGasAlgorithmDatasTask");
	protected final static String SEND_ACTION_CODE="CloseGasDispersionAlgorithmServiceReturn";
	protected final static String SEND_TOPIC_NAME = "ESM27AlgorithmToService";
	
	@Override
	public boolean isHandle(MQMessageOfESM27 t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfESM27 t) {
		try {
		autoPushGasAlgorithmDatasTask.setCron(null); 		
		logger.info("关闭推送气体任务成功");
		sendReturnMessage(t.getTimestamp(),true,null);
		}catch(Exception e) {
			sendReturnMessage(t.getTimestamp(),false,e.getMessage());
		}
		return null;
	}
	
	private void sendReturnMessage(long time,boolean isSuccess,String msg) {
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(SEND_ACTION_CODE);
		message.setTimestamp(time);
		message.setAwsPostdata(msg);
		message.setSuccess(isSuccess);

		String json = JSON.toJSONString(message);
		topicSender.send(SEND_TOPIC_NAME, json);
	}
}